import express from 'express'
import { getBotReply } from '../../../api/index.js';
import { addSql, getResult, listSql, onDuplicByFiled, putSql } from '../../../util/operateSql.js';
import { postGPT } from '../../../api/robot/weixin.js';
var router = express.Router();
var TABLE_NAME =  'robot.robots'

router.post('/tianxing',(req, res, next) => {
  const params = {
    key: process.env.TIANXING_KEY,
    question: req.body.text
  }
  getBotReply(params).then((result) => {
    
    res.json(req.app.locals.success(result.newslist[0].reply))
  }).catch((err) => {
    res.json(req.app.locals.error(err))
  });
})

router.post('/login',(req, res, next) => {
  const body = req.body
  body.weId = body.id
  const sql = onDuplicByFiled(TABLE_NAME,{...body})
  getResult(sql).then((result) => {
    
  }).catch((err) => {
    
    
  });
})

router.get('/list',(req,res,next) => {
  const {pageIndex=1 , pageSize=10} = req.query
  const sql = listSql(TABLE_NAME,{pageIndex,pageSize})
  getResult(sql).then((result) => {
    res.json(req.app.locals.success(result))
  }).catch((err) => {
    res.json(req.app.locals.error(err))
  });
})


router.post('/update',(req,res,next) => {
  const body = req.body
  const sql = putSql(TABLE_NAME, body)
  
  getResult(sql).then((result) => {
    res.json(req.app.locals.success('修改成功'))
  }).catch((err) => {
    res.json(req.app.locals.error(err,'修改失败'))
  });
})

/**
 * 输入微信号生成登录二维码
 */
router.post('/showCode',(req,res,next) => {
  const body = req.body
  const sql = addSql(TABLE_NAME, body)
  getResult(sql).then((result) => {
    res.json(req.app.locals.success(result))
  }).catch((err) => {
    res.json(req.app.locals.error(err,'::Error'))
  });
})

router.post('/gpt',(req,res,next) => {
  const body = req.body
  const key = process.env.GPT_KEY || ''
  const header = {
    "Authorization": "Bearer "+key
  }
  postGPT({
    model: "gpt-3.5-turbo",
    messages: [{"role": "user", "content": body.content || ''}]
  },header).then((result) => {
    res.json(req.app.locals.success(result))
  }).catch((err) => {
    console.log('err: ', err);
    res.json(req.app.locals.error(err,'::Error'))
  });
  
})


export default router